// ==UserScript==
// @name         Quora评论
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://www.quora.com/*
// @grant        GM_xmlhttpRequest
// @require      https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js
// @require      https://gitee.com/starric/picbed/raw/master/src/quoraddB64.js
// @require      https://gitee.com/starric/picbed/raw/master/src/md5.js
// @require      https://gitee.com/starric/picbed/raw/master/src/html2canvas.js



// ==/UserScript==



(function() {

    $(document).ready(()=>{
        initApp();
    })

    function initApp(){
        $(
            '<div id="whatisthis" style="color: #fff;display: flex;justify-content: center;align-items: center;position: fixed; width: 50px; height: 50px; bottom: 20px; right: 20px; background-color: #50afee;z-index:9999;border-radius: 50%;cursor:Pointer;user-select:none;">'
            +'✨</div>'
        ).appendTo("body");

        $('#whatisthis').mouseover(()=>{
            $("#whatisthis").css('background-color', '#3c96d3')
        })
    
        $('#whatisthis').mouseleave(()=>{
            $("#whatisthis").css('background-color', '#50afee')
        })
    
        $('#whatisthis').mousedown(()=>{
            $("#whatisthis").css('background-color', '#3283b9')
        });
    
        $('#whatisthis').mouseup(()=>{
            $("#whatisthis").css('background-color', '#3c96d3');
            $("#whatisthis").animate({
                width: '50px',
                height: '50px',
                bottom: '20px',
                right: '20px',
                borderRadius: '10%'
            }, 300);
            setTimeout(()=>{
                main().then(()=>{
                    $("#whatisthis").animate({
                        width:'50px',
                        height:'50px',
                        bottom: '20px',
                        right: '20px',
                        borderRadius: '50%'
                    }, 300);
                });
            },300);
        })
    }

    var ans_count = 1;

    async function main() {
        rightPannel();
        var aqbox = $(".q-text.qu-display--flex.qu-px--large.qu-pb--large.qu-flexDirection--row.qu-fontSize--regular");
        aqbox.css('width', 'unset');
        var qutitle = $('.q-text.qu-bold.qu-fontSize--xlarge.qu-color--gray_dark_dim.qu-passColorToLinks.qu-userSelect--text.qu-lineHeight--regular');
        if(!qutitle.attr('ready')){
            qutitle.prevAll().remove();
            var qutitleParent = qutitle.parent();
            qutitleParent.css({
                padding: '5px',
                borderBottom: '#eeeeee 5px solid',
                outline: '1px solid #eeeeeedf',
                position: 'relative'
            });
            qutitleParent.prevAll().remove();
            qutitleParent.before(
                '<div id="i-give-u" style="width:100%;background: rgb(255, 212, 160);display: flex;align-items: center;color:#fff;font-size: 30px;padding:3px 10px;box-sizing: border-box;">'+('问题')+'</div>'
            );
            qutitleParent.before(
                '<button id="bdtranslate-ques" style="margin:10px 10px 10px 0">百度翻译</button>'
                +'<button id="ques-add-movab-text" style="margin:10px 0">添加</button>'
            );
            var qubar = $('<div id="qu-bottom-bar" style="width: 100%;height: 20px; background: #eeeeee;margin-top: 10px;cursor: n-resize;"></div>');
            // magicQubar(qubar);
            magicBar(qubar, '.q-box')
            qutitleParent.after(qubar);
        }
        qutitle.attr('ready', true);
        var anns = $(".q-box.qu-pb--small.qu-borderBottom")
                    .not(".qu-bg--raised")
                    .not(".spacing_log_question_page_ad")
                    .children('.q-box.qu-pt--medium.qu-pb--tiny')
                    ;
        for (let i = 0; i < anns.length; i++) {
            const e = anns.eq(i);
            e.find('.q-text.qu-cursor--pointer.qt_read_more.qu-color--blue_dark.qu-fontFamily--sans.qu-bg--white.qu-hover--textDecoration--underline')
             .trigger('click');
            e.prevAll().remove();
            e.before(
                '<div id="ans-controll-bar" style="top:50px;position: sticky;z-index:299;background: #fff;border-bottom: 1px solid #eeeeee;">'+
                '<div id="i-give-u" style="width:100%;background: rgb(255, 212, 160);display: flex;align-items: center;color:#fff;font-size: 30px;padding: 5px;box-sizing: border-box;">'+(ans_count+i)+'</div>'
                +'<button id="bdtranslate-ann" style="margin:10px 10px 10px 0">百度翻译</button>'
                +'<button id="ann-add-movab-text" style="margin:10px 0">添加</button>'
                +'<button id="ann-contenteditable" style="margin:10px 10px 10px 10px">编辑:off</button>'
                +'<button id="save-ans-to-img" style="margin:10px 0 10px 30px">保存为图片</button>'
                +'</div>'
            );
            e.nextAll().hide();
            e.find('.q-text.qu-fontSize--regular.qu-truncateLines--3.qu-passColorToLinks').removeClass('qu-truncateLines--3');
            e.find('.q-inlineFlex.qu-ml--small.qu-alignItems--center').replaceWith(quoraSvg());
            var warp1 = $('<div id="ann-box" style="position: relative;"></div>');
            warp1.css({
                padding: '5px 5px 0 5px',
                borderBottom: '#eeeeee 5px solid',
                outline: '1px solid #eeeeeedf'
            })
            var bar = $('<div id="ann-bottom-bar" style="width: 100%;height: 20px; background: #eeeeee;margin-top: 10px;cursor: n-resize;"></div>');
            magicBar(bar, '#ann-box');
            e.parent().append(bar)
            e.wrap(warp1)
        }
        ans_count += anns.length;
    }

    $('body').on('click', '#bdtranslate-ques', (e)=>{
        var ques = $(e.target).parent().find('.q-text.qu-bold.qu-fontSize--xlarge.qu-color--gray_dark_dim.qu-passColorToLinks.qu-userSelect--text.qu-lineHeight--regular').text();
        bdtranslator(ques, (res)=>{
            res = JSON.parse(res.response)
            if(res['error_code']) return alert("百度翻译："+res['error_msg']);
            console.log(res)
            var r = res.trans_result[0].dst
            // console.log(r)
            // $('#translate-raw-data').val('')
            $('#translate-raw-data').val(r)
        });
    })

    $('body').on('click', '#ques-add-movab-text', (e)=>{
        var qelem = $(e.target).parent().children('.q-box');
        // console.log(qelem[0])
        var elem = $('<div id="movab-text" style="position: absolute;left: 0;top: 0;cursor: move;color: red;font-size: 25px;background: rgba(211, 210, 210, 0.5);font-weight: bold;">双击以编辑</div>');
        elem.appendTo(qelem);
        movableDOM(elem);
    })

    // 添加可移动编辑框
    $('body').on('click', '#ann-add-movab-text', (e)=>{
        var ans = $(e.target).parents().children('#ann-box');
        // console.log(ans.offset().top-$(document).scrollTop())
        var ans_hideH = ans.offset().top-$(document).scrollTop();
        var top_m = 0;
        if(ans_hideH < 150) top_m = -ans_hideH + 150;
        // console.log(top_m)
        var elem = $('<div id="movab-text" style="position: absolute;left: 0;top: '+top_m+'px;cursor: move;color: red;font-size: 25px;background: rgba(211, 210, 210, 0.5);font-weight: bold;">双击以编辑</div>');
        elem.appendTo($(e.target).parents().children('#ann-box'));
        movableDOM(elem);
    });

    // 百度翻译回答
    $('body').on('click', '#bdtranslate-ann', (e)=>{
        var ans = $(e.target).parents().children('#ann-box').find('.q-relative.spacing_log_answer_content');
        var data = ans.text();
        bdtranslator(data, (res)=>{
            res = JSON.parse(res.response)
            if(res['error_code']) return alert("百度翻译："+res['error_msg']);
            console.log(res)
            var r = res.trans_result[0].dst
            // console.log(r)
            // $('#translate-raw-data').val('')
            $('#translate-raw-data').val(r)
        });
    });

    // 切换是否可编辑回答内容
    $('body').on('click', '#ann-contenteditable', (e)=>{
        var qelem = $(e.target).parents().children('#ann-box');
        var f = qelem.attr('contenteditable');
        if(f != 'true'){
            $(e.target).text('编辑:on');
            qelem.attr('contenteditable', true);
        } else {
            $(e.target).text('编辑:off');
            qelem.attr('contenteditable', false);
        }
    })

    // 保存
    $('body').on('click', '#save-ans-to-img', (e)=>{
        var qelem = $(e.target).parents().children('#ann-box');
        var votebar = qelem.find('.q-box.qu-bg--white.qu-zIndex--action_bar.qu-borderTop.qu-boxShadow--n_small');
        // console.log(votebar);
        votebar.removeClass('qu-borderTop qu-boxShadow--n_small');
        votebar.css('position', 'unset');
        htmlElem2canvas(qelem[0]);
        votebar.addClass('qu-borderTop qu-boxShadow--n_small');
        votebar.css('position', 'sticky');
    })

    // 双击可移动编辑框
    $('body').on('dblclick', '#movab-text', (e)=>{
        var el = $(e.target)
        cmtCustom(el);
        el.attr('contenteditable',"true")
        el.css('cursor','auto')
        el.css('background','rgba(98, 192, 255, 0.5)')
        el.off('mousedown')
    });

    // 可以的编辑框失焦
    $('body').on('focusout', '#movab-text', (e)=>{
        var el = $(e.target)
        // console.log(el[0])
        el.attr('contenteditable',"false")
        el.css('cursor','move')
        el.css('background','rgba(211, 210, 210, 0.5)')
        movableDOM(el)
    });

    function quoraSvg(){
        return '<img src="'+quoraddB64()+'" alt="" style="width:32px"></img>'
    }
    
})();

function magicBar(e, target){
    e.mouseover((el)=>{
        $(el.target).css({
            background: '#cccccc'
        })
    })
    e.mouseleave((el)=>{
        $(el.target).css({
            background: '#eeeeee'
        })
    })
    e.mousedown(()=>{
        $('body').css('cursor', 'n-resize');
        //获取鼠标按下的时候左侧偏移量和上侧偏移量
        var old_top = event.pageY;//竖直偏移量
        var old_pb = e.parent().children(target).css('padding-bottom')
        old_pb = parseInt(old_pb);
        // console.log(old_left,old_top,old_position_left,old_position_top)
        var move_lock = false
        $(document).mousemove(function(event){
            if(move_lock) return console.warn("阻止了可能导致卡顿的拖动事件");
            move_lock = true
            var new_top = event.pageY;//新的鼠标竖直方向上的偏移量
            //计算发生改变的偏移量是多少
            var change_y = new_top - old_top;
            var new_pb = old_pb + change_y;
            // 上限制
            if(new_pb<0){//padding-bottom>=0
                new_pb = 0;
            }
            e.parent().children(target).css('padding-bottom', new_pb+'px');
            move_lock = false
        })
    })
    $(document).mouseup(function(){
        $('body').css('cursor', 'auto');
        $(document).off("mousemove");
    })
}

var editingMovabText = false;
function cmtCustom(e){
    editingMovabText = e;
    var fs = e.css('font-size');
    fs = parseInt(fs)
    $("#text-fs").val(fs);
}

$('body').on('click', '#text-fs-bigger', ()=>{
    if(!editingMovabText) return alert('没有选中的元素');
    $(editingMovabText).focus()
    var fs = editingMovabText.css('font-size');
    fs = parseInt(fs)
    $("#text-fs").val(fs)
    fs += 1;
    $("#text-fs").val(fs)
    editingMovabText.css('font-size', fs+'px')
})
$('body').on('click', '#text-fs-smaller', ()=>{
    if(!editingMovabText) return alert('没有选中的元素');
    var fs = editingMovabText.css('font-size');
    fs = parseInt(fs)
    $("#text-fs").val(fs)
    fs -= 1;
    $("#text-fs").val(fs)
    editingMovabText.css('font-size', fs+'px')
})
$('body').on('click', '#confirm-text-fs', ()=>{
    if(!editingMovabText) return alert('没有选中的元素');
    editingMovabText.css('font-size', $("#text-fs").val()+'px')
})
$('body').on('click', '#delete-current-removab-text', ()=>{
    if(!editingMovabText) return alert('没有选中的元素');
    editingMovabText.remove()
    editingMovabText = false;
})


function rightPannel() {
    var rig = $('.q-box.puppeteer_test_question_main')
        .children('.q-text.qu-display--flex.qu-px--large.qu-pb--large.qu-flexDirection--row.qu-fontSize--regular')
        .children('.q-box').eq(1);
    var rp_status = rig.attr('ready');
    if(rp_status == 'true') return;
    rig.css({
        width:'100%'
    });
    rig.empty();
    var rpb = $('<div id="right-float-pannel"></div>')
    rpb.css({
        overflowY:'scroll',
        height:'80vh',
        width:'100%',
        boxSizing:'border-box',
        padding:'10px',
        top: '80px',
        position: 'sticky'
    })
    var titleStyle = 'style="font-size: 18px;margin: 10px 0;"'
    var buttonStyle = 'style="margin: 5px 5px 5px 0"'
    rpb.append('<div id="translate-res">'
    +'<div '+titleStyle+'>翻译结果</div><button id="translate-text-status" status="1">收起</button>'
    +'<div><textarea id="translate-raw-data" style="resize: vertical;font-size: 18px;line-height: 1.5;" rows="14"></textarea></div>'
    +'</div>')
    rpb.append('<div id="text-style-controller">'
    +'<div '+titleStyle+'>字体大小</div>'
    +'<div><button id="text-fs-bigger" '+buttonStyle+'>更大</button><button id="text-fs-smaller" '+buttonStyle+'>更小</button></div>'
    +'<div><input id="text-fs" type="text"> <button id="confirm-text-fs" '+buttonStyle+'>确定</button></div>'
    +'<div style="margin-top: 20px;"><button id="delete-current-removab-text" style="color: red;">删除元素</button></div>'
    +'</div>')
    rpb.appendTo(rig)

    $('#translate-text-status').click((e)=>{
        var btn = $(e.target)
        var sts = btn.attr('status')
        // console.log(sts)
        if(sts == '1'){
            btn.text('展开')
            $('#translate-raw-data').hide()
            btn.attr('status', '0')
        } else {
            btn.text('收起')
            $('#translate-raw-data').show()
            btn.attr('status', '1')
        }
    })
    rig.attr('ready', true);
}

function movableDOM(e){
    e.mousedown(function(event){
        //获取鼠标按下的时候左侧偏移量和上侧偏移量
        var old_left = event.pageX;//左侧偏移量
        var old_top = event.pageY;//竖直偏移量

        //获取鼠标的位置
        var old_position_left = $(this).position().left;
        var old_position_top = $(this).position().top;
        // console.log(old_left,old_top,old_position_left,old_position_top)
        $(document).mousemove(function(event){
            var new_left = event.pageX;//新的鼠标左侧偏移量
            var new_top = event.pageY;//新的鼠标竖直方向上的偏移量

            //计算发生改变的偏移量是多少
            var chang_x = new_left - old_left;
            var change_y = new_top - old_top;

            //计算出现在的位置是多少

            var new_position_left = old_position_left + chang_x;
            var new_position_top = old_position_top + change_y;

            // 左限制
            if(new_position_left<0){//左边的偏移量小于0的时候设置 左边的位置为0
                new_position_left=0;
            }

            e.css({
                left: new_position_left + 'px',
                top: new_position_top + 'px'
            })
        })

        e.mouseup(function(){
            $(document).off("mousemove");
        })
    })
}

function kickEmoji(s) {
    var reg = /(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])/g;
    return s.replaceAll(reg, '')
    // return s
}

function bdtranslator(query, successCallback, from="auto", to="zh") {
    var appid = '20201002000579022';
    var key = 'VL_x3kmLnKr_Vf5eolTg';
    var salt = (new Date).getTime();
    // var query = 'apple';
    // 多个query可以用\n连接  如 query='apple\norange\nbanana\npear'
    // var from = 'en';
    // var to = 'zh';
    query = kickEmoji(query)
    console.log([query,from,to])
    var str1 = appid + query + salt +key;
    var sign = MD5(str1);
    var payload = {
        q: query,
        appid: appid,
        salt: salt,
        from: from,
        to: to,
        sign: sign
    }
    var params = ""
    for(var key in payload){
        params = params+key+"="+encodeURIComponent(payload[key])+"&"
    }
    GM_xmlhttpRequest({
        method: 'POST',
        url: 'http://api.fanyi.baidu.com/api/trans/vip/translate',
        headers: {
            "Content-Type": "application/x-www-form-urlencoded"
        },
        data: params,
        onload: successCallback
    });
}


function htmlElem2canvas(element) {
    var options = {
        "scrollX": 0,
        // "scrollY": 0,
        "useCORS": true,
        "logging": false,
        "scale": 2,
        "scrollY": -1 * window.scrollY
    };
    /*  */
    // console.log('hi!')
    //   console.log(config)
    //   console.log(options)
    html2canvas(element, options).then(canvas => {
        if (canvas) {
            var res = canvas.toDataURL();
            var dom = document.createElement('a');
            dom.setAttribute("href", res);
            dom.setAttribute("download", "下载");
            dom.click();
        } else {
            alert('保存失败');
        }
    })
}